package com.pubinfo.passbook.common.service.ruler.impl;

import cn.hutool.core.collection.CollUtil;
import com.pubinfo.passbook.common.entity.TRuleFormula;
import com.pubinfo.passbook.common.mapper.TSourcePassbookMapper;
import com.pubinfo.passbook.common.model.bo.witeoff.CityInfo;
import com.pubinfo.passbook.common.model.ruler.PayInformation;
import com.pubinfo.passbook.common.service.aviator.AviatorScriptService;
import com.pubinfo.passbook.common.service.master.TRuleGenusService;
import com.pubinfo.passbook.common.service.ruler.CheckService;
import com.pubinfo.passbook.common.service.ruler.InformationService;
import com.pubinfo.passbook.common.service.ruler.RuleShengGongSiService;
import com.pubinfo.passbook.common.utils.UccpUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

@Service
@Slf4j
public class RuleShengGongSiServiceImpl implements RuleShengGongSiService {
  
  @Autowired
  CheckService checkService;
  @Autowired
  AviatorScriptService scriptService;
  @Autowired
  InformationService informationService;
  @Autowired
  TRuleGenusService genusService;
  @Autowired
  CheckService ruleService;
  @Autowired
  TSourcePassbookMapper tSourcePassbookMapper;
  
  @Override
  public BigDecimal benbu(CityInfo info, Map<String, Object> paramEnv, List<PayInformation> payInformations) {
    BigDecimal sum = BigDecimal.ZERO;
    Set<String> detailsSet = new HashSet<>();
    //总金额
    for (PayInformation payInformation : payInformations) {
      //如果是竖版的，并且没有使用医保，则直接返回0;
      if (StringUtils.isNotBlank(payInformation.getPatientMedicalInsuranceType())) {
        if (!payInformation.getPatientMedicalInsuranceType().contains("医保")) {
          //  details.append("没有使用医保,不参与报销;");
          detailsSet.add("没有使用医保,不参与报销");
          continue;
        }
      }

      BigDecimal totalAmount = payInformation.getTotalAmount();
      if (totalAmount.equals(new BigDecimal(-0.0000999))) {
        paramEnv.put("isNeedAudit", true);
        totalAmount = BigDecimal.ZERO;
      }
      //个人现金支付
      BigDecimal ownPayAmount = payInformation.getOwnPayAmount();
      if (ownPayAmount.equals(new BigDecimal(-0.0000999))) {
        paramEnv.put("isNeedAudit", true);
        ownPayAmount = BigDecimal.ZERO;
      }

      //自费金额
      BigDecimal selfpaymentCost = payInformation.getSelfpaymentCost();
      if (selfpaymentCost.equals(new BigDecimal(-0.0000999))) {
        paramEnv.put("isNeedAudit", true);
        selfpaymentCost = BigDecimal.ZERO;
      }
    
      //自理金额
      BigDecimal selfpaymentCare = payInformation.getSelfpaymentCare();
      if (selfpaymentCare.equals(new BigDecimal(-0.0000999))) {
        paramEnv.put("isNeedAudit", true);
        selfpaymentCare = BigDecimal.ZERO;
      }
    
      //统筹基金支付金额
      BigDecimal fundPayAmount = payInformation.getFundPayAmount();
      if (fundPayAmount.equals(new BigDecimal(-0.0000999))) {
        paramEnv.put("isNeedAudit", true);
        fundPayAmount = BigDecimal.ZERO;
      }
    
      //本年支付
      BigDecimal currPayment = payInformation.getIndividualAccountCurrPayment();
      if (currPayment.equals(new BigDecimal(-0.0000999))) {
        paramEnv.put("isNeedAudit", true);
        currPayment = BigDecimal.ZERO;
      }

      BigDecimal indagation = informationService.getAmountByCostName(payInformation.getEInvoiceId());
      if (indagation.equals(new BigDecimal(-0.0000999))) {
        paramEnv.put("isNeedAudit", true);
        indagation = BigDecimal.ZERO;
      }
    
      //诊查费
      PayInformation pay = payInformations.get(0);
      String idNo = pay.getPayerPartyCode(); //报账人的身份证号
      paramEnv.put("totalAmount", totalAmount);
      paramEnv.put("ownPayAmount", ownPayAmount);
      paramEnv.put("selfpaymentCost", selfpaymentCost);
      paramEnv.put("selfpaymentCare", selfpaymentCare);
      paramEnv.put("fundPayAmount", fundPayAmount);
      paramEnv.put("currPayment", currPayment);
      BigDecimal itemSum = BigDecimal.ZERO;
      String key;
      //劳模  总金额-本年支付-统筹基金支付-自费
      if (ruleService.isSpecialUser(info.getDistrictName(), idNo, "internal_role")) {
        //itemSum = itemSum.add(scriptService.executeNotNegativeNumber("totalAmount-currPayment-fundPayAmount-selfpaymentCost", paramEnv));
        key = "benbu_special";
      } else {
        //一般病种：总金额-本年支付-统筹基金支付-自理-自费
        //itemSum = itemSum.add(scriptService.executeNotNegativeNumber("totalAmount-currPayment-fundPayAmount-selfpaymentCare-selfpaymentCost", paramEnv));
        key = "benbu_general";
      }
      TRuleFormula formula = (TRuleFormula) paramEnv.get(key);
      itemSum = scriptService.execute(formula.getFormula(), paramEnv);
      detailsSet.add(formula.getDetalis());
      BigDecimal exceed = null;
      //门诊含诊查费最多只报销10块
      if (pay.getReimbursementType() == 0)
      {
        exceed = indagation.intValue() > 10 ? new BigDecimal("10") : indagation;
        // details.append(formula.getDetalis());
        if (itemSum.compareTo(BigDecimal.ZERO) == 1 && indagation.compareTo(BigDecimal.ZERO)  == 1) { //如果按公式计算大于0，并且诊查费大于0，则到小的部分，
          //诊查费超出部分   诊查费上限10   超过部分不报销
          //再按公式计算，取两者最小值
          itemSum = exceed.min(itemSum);
        }
      }
      //厅局级  现金支付-诊查费超过部分
      if (checkService.isSpecialUser(info.getDistrictName(), pay.getPayerPartyCode(), "internal_role")) {
        itemSum = itemSum.add(ownPayAmount.subtract(exceed));
      }
  
      if (UccpUtil.isTimeout(payInformation.getIssueDate())) {
        itemSum = BigDecimal.ZERO;
      }
      payInformation.setReimbursableSum(itemSum);
      tSourcePassbookMapper.updateReimbursableSumById(payInformation);
      sum = sum.add(itemSum);
    }
    if (sum.intValue() < 0) {
      sum = new BigDecimal(0);
    }

    paramEnv.put("user-detalis", CollUtil.join(detailsSet, ";"));
    return sum;
  }
  
}
